<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\AddCartRequest;
use App\Http\Requests\CartBuyRequest;
use App\Model\ShopCartModel;
use App\Model\ShopGoodModel;
use App\Model\ShopOrder;
use App\Model\ShopOrderFs;
use App\Model\ShopOrderFstModel;
use App\Model\SkuModel;
use App\Model\StoreGoodLog;
use App\Model\StoreGoodModel;
use App\Model\StoreModel;
use App\Model\UserModel;
use App\Model\UserWalletModel;
use App\Services\Msfl;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;


class CartController extends Controller
{
//    private $uid;
    public function __construct(Request $request)
    {
        $this->uid = $request->header('uid',null);
    }
    //加入购物车
    public function add_cart(AddCartRequest $request)
    {
        $uid = $this->uid;
        $shop_id = $request->get('shop_id');//商品id
        $sku_id = $request->get('sku_id',0);//sku_id
        $num = $request->get('num');//购买数量

        //判断该商品是否存在
        if(empty($sku_id)){
            $sku_id = 0;
			$store = StoreGoodModel::where('gid',$shop_id)->sum('num'); //云仓库库存
			$b_store = ShopGoodModel::where('id',$shop_id)->value('num'); //实际库存
        }

        if($sku_id > 0){
//            $sku = SkuModel::where('gid',$shop_id)->where('id',$sku_id)->first();
//            if(empty($sku)){
//                return ['code'=>0,'msg'=>retStrInfo(209)];//该商品库存不足
//            }
			$store = StoreGoodModel::where('sku_id',$sku_id)->where('gid',$shop_id)->sum('num');
			$b_store = SkuModel::where('id',$sku_id)->value('sum');
        }
		if($store+$b_store < $num){
			return ['code'=>0,'msg'=>retStrInfo(209)];//该商品库存不足
		}

        if(!empty($sku_id)){
            $is_sku = 1; //多规格
            $has = ShopCartModel::where('uid', $uid)->where('gid', $shop_id)->where('sku_id',$sku_id)->first();
        }else{
            $is_sku = 0; //单规格
            $has = ShopCartModel::where('uid', $uid)->where('gid', $shop_id)->first();
        }
        $shop = ShopGoodModel::where('id',$shop_id)->first();
        if($shop->state != 1 || empty($shop)){
            return ['code'=>0,'msg'=>retStrInfo(200)];//该商品已下架
        }
        //购物车商品数量不能超过20
        $count = ShopCartModel::where('uid', $uid)->count();
        if ($count > 20) {
            return ['code'=>0,'msg'=>retStrInfo(203)];//购物车商品过多请先清理;
        }
        //加入购物车
        DB::beginTransaction();
        try {

            if (!empty($has)) {
                $has->update([
                    'num' => $has->num + $num,
                ]);
            } else {
                $cart = new ShopCartModel();
                $cart->uid = $uid;
                $cart->gid = $shop_id;
                $cart->sku_id = $sku_id;
                $cart->num = $num;
                $cart->is_sku = $is_sku;
                $cart->save();
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['code'=>0,'msg'=>$exception->getMessage()];//抛出异常
        }
        return ['code'=>1,'msg'=>retStrInfo(201)];//成功加入购物车
    }
    //购物车列表
    public function cart_list()
    {
        $uid = $this->uid;
        $list = ShopCartModel::where('uid',$uid)->get();
        $data = [];
        foreach ($list as $k => $v){
            $shop = ShopGoodModel::where('id',$v->gid)->first();
            $data[$k]['cart_id'] = $v->id;
            $data[$k]['product_id'] = $v->gid;
            $data[$k]['name'] = $shop->name;
            if($shop->title){
            	$data[$k]['name'] = $shop->title;
			}
            $data[$k]['sell_price'] = number_format($shop->sell_price,2,".","");
            $data[$k]['cost_price'] = number_format($shop->cost_price,2,".","");
            $data[$k]['sku_id'] = 0;
            $data[$k]['sku'] = "无";
            if($shop->is_attr == 1){
                $sku = SkuModel::where('id',$v->sku_id)->first();
                $data[$k]['sku_id'] = $sku->id;
                $data[$k]['sku'] = $sku->property;
                $data[$k]['sell_price'] = number_format($sku->sell_price,2,".","");
                $data[$k]['cost_price'] = number_format($sku->cost_price,2,".","");
            }
            $data[$k]['picpath'] = $shop->picsname;
            $data[$k]['num'] = $v->num;
        }
        return ['code'=>1,'data'=>$data];
    }
    //编辑购物车 (苹果接口)
    public function update_cart(Request $request)
    {
        $uid = $this->uid;
        $product_ids = $request->get('cart_ids');//数组格式
//        return ['code'=>1,'msg'=>'','data'=>$product_ids];
        foreach ($product_ids as $product_id) {
            $is_has = ShopCartModel::where('uid', $uid)->where('id', $product_id)->first();
            if(empty($is_has)){
                return ['code'=>0,'msg'=>retStrInfo(202)];
            }
            ShopCartModel::where('id', $product_id)->delete();
        }
        return ['code'=>1,'msg'=>retStrInfo(201)];
    }

    //编辑购物车 (安卓)
    public function update_cart_an(Request $request)
    {
        $uid = $this->uid;
        $product_ids = $request->get('cart_ids');//数组格式 1,2
        //拆分
        $arr = explode(",",$product_ids);
//        dump($arr);
        foreach ($arr as $product_id) {
            $is_has = ShopCartModel::where('uid', $uid)->where('id', $product_id)->first();
            if(empty($is_has)){
                return ['code'=>0,'msg'=>retStrInfo(202)];
            }
//            dump($product_id);
            ShopCartModel::where('id', $product_id)->delete();
        }
        return ['code'=>1,'msg'=>retStrInfo(201)];
    }

    //购物车内下单
    public function cart_buy(CartBuyRequest $request)
    {
        $uid = $this->uid;
        $name = $request->get('name');
        $paypass = $request->get('paypass');
        $phone = $request->get('phone');
        $address = $request->get('address');
        $products = $request->get('products');
        $in_out = $request->get('in_out');
        $type = $request->get('type',null);
        if($type == 1){
            $products = json_decode($products,true);
        }

        $invoice_id = $request->get('invoice_id');
        if(!Hash::check($paypass,UserModel::where('id',$uid)->value('paypass'))){
            return ['code'=>0,'msg'=>retStrInfo(56)];//支付密码错误
        }

        $user = UserModel::where('id',$uid)->first();
        if($user['is_auth'] != 1){
            return ['code'=>0,'msg'=>'当前尚未实名认证，请认证完之后再下单'];
        }
        DB::beginTransaction();
        try{
            //大订单
            $big_order = new ShopOrder();
            $big_order->sn = ShopOrder::make_no();
            $big_order->uid = $uid;
            $big_order->all_price = 0;
            if(!empty($invoice_id)){
                $big_order->invoice_id = $invoice_id;
            }
            $big_order->save();
            $oid = $big_order->id;
            foreach ($products as $k => $product){
                //验证库存是否足够
                if(empty($product['sku_id'])){
                    $store = StoreGoodModel::where('gid',$product['product_id'])->sum('num'); //云仓库库存
                    $b_store = ShopGoodModel::where('id',$product['product_id'])->value('num'); //实际库存
                }else{
                    $store = StoreGoodModel::where('sku_id',$product['sku_id'])->where('gid',$product['product_id'])->sum('num');
                    $b_store = SkuModel::where('id',$product['sku_id'])->value('sum');
                }
//				return ['code'=>0,'msg'=>retStrInfo(209)];//商品库存不足
                if($store + $b_store < $product['num']) {
					return ['code'=>0,'msg'=>retStrInfo(209)];//商品库存不足
                }
                $store_cy['store'] = $store;
                $store_cy['b_store'] = $b_store;
                $store_cy['num'] = $product['num'];

                //小订单
                    $shop = ShopGoodModel::where('id',$product['product_id'])->where('state',1)->first();
                    if(empty($shop)){
                    return ['code'=>0,'msg'=>retStrInfo(200)];//商品已下架
                }
                $sku = SkuModel::where('id',$product['sku_id'])->first();
                $small_order = new ShopOrderFs();
                $small_order->oid = $oid; //大订单id
                $small_order->gid = $product['product_id']; //商品id
                $small_order->shop_name = $shop->name;   //商品名字
				if($shop->title){
					$small_order->shop_name = $shop->title;
				}
                $small_order->shop_pic = $shop->picpath.$shop->picname; //商品图片
                $small_order->num = $product['num']; //商品数量
                $small_order->single_price = $shop->sell_price; //销售价
                $small_order->all_price = bcmul($shop->sell_price,$product['num'],5); //销售总价
                $small_order->sn_son = ShopOrderFs::make_no(); //子订单号
                $small_order->uid = $uid; //用户id
                $small_order->name = $name; //收货人
                $small_order->phone = $phone; //手机号
                $small_order->address = $address; //地址
                if(!empty($sku)){
                    $small_order->sku_id = $product['sku_id'];  //sku_id
                    $small_order->shop_attr = $sku->property;
                    $small_order->single_price = $sku->sell_price; //销售价
                    $small_order->all_price = bcmul($sku->sell_price,$product['num'],5); //销售总价
                    $small_order->shop_attr = $sku->property; //商品规格
                }

                $small_order->save();
                //购物车去掉这个商品
                //如果是购物车外就不用删
                if(empty($in_out)){
                    if(!empty($sku)){
                        ShopCartModel::where('uid',$uid)->where('sku_id',$sku->id)->delete();
                    }else{
                        ShopCartModel::where('uid',$uid)->where('gid',$product['product_id'])->delete();
                    }
                }


                //商品加销量减库存
                ShopGoodModel::min($product['product_id'],$product['num']);

                //sku加销量减库存
                if(!empty($product['sku_id'])){
                    SkuModel::min($product['sku_id'],$product['num']);
                }

                //云仓库
                $msfl = new Msfl();
                if(!empty($sku)){
                    $msfl->min_store($product['product_id'],$product['sku_id'],$product['num'],$small_order->id);
                }else{
                    $msfl->min_store($product['product_id'],"",$product['num'],$small_order->id);
                }



            }
            //修改订单总金额
            $all_price = ShopOrderFs::where('oid',$oid)->sum('all_price');
            ShopOrder::where('id',$oid)->update(['all_price'=>$all_price]);
            //判断用户余额是否足够
            $balance = UserWalletModel::where('uid',$uid)->value('money');
            if($all_price > $balance){
                return ['code'=>0,'msg'=>'现金余额不足'];//抛出异常
            }
            //扣除用户货款
            /*
             * uid 用户id
             * num 数额
             * sign 加或减
             * msg 描述
             * type 1现金 2货款
             * status type=1 1充值 2提现 3转货款 4成为VIP 5销售奖 6领导奖 7教育奖 8云仓库收益 9后台充值  type=2 3转货款 10入库 11下单 12创客奖 13累计充值够10000返利388
             * dy_table 对应表
             * dy_id 对应id
             */
			$msfl->person_yj($uid,$all_price);
			$msfl->father_yeji($uid,$all_price);//教育奖业绩
			UserWalletModel::handleAccount($uid,$all_price,'-','用户购物车下单','1','11');
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['code'=>0,'msg'=>$exception->getMessage()];//抛出异常
        }
        
        $data['all_price'] = round($all_price,2); //总价
        $data['sn'] = $big_order->sn; //订单编号
        $data['created_at'] = $big_order->created_at->format('Y-m-d H:i:s'); //下单时间
        return ['code'=>1,'msg'=>retStrInfo('207'),'data'=>$data,'data_cy'=>$store_cy];//下单成功
    }

    //购物车入库(验证密码,实名认证,开通云仓库,云仓库状态正常)
    public function add_store(Request $request)
    {
        $uid = $this->uid;
        $type = $request->get('type',null);
        $store = StoreModel::where('uid',$uid)->where('state',1)->first();
        if(empty($store)){
            return ['code'=>0,'msg'=>retStrInfo(210)];//未开通云仓库或者云仓库冻结
        }
        $sid = $store->id;
        $paypass = $request->get('paypass');
        $products = $request->get('products');
        //安卓传的json
        if($type == 1){
            $products = json_decode($products,true);
        }
        if(empty($paypass) || empty($products)){
            return ['code'=>0,'msg'=>retStrInfo(202)];//数据错误
        }

        if(!Hash::check($paypass,UserModel::where('id',$uid)->value('paypass'))){
            return ['code'=>0,'msg'=>retStrInfo(56)];//支付密码错误
        }
        //是否实名
        $user = UserModel::where('id',$uid)->first();
        if($user->is_auth != 1){
            return ['code'=>0,'msg'=>retStrInfo(95)];//没有实名认证
        }
        //是否开通云仓库
        $store = StoreModel::where('uid',$uid)->first();
        if(empty($store)){
            return ['code'=>0,'msg'=>retStrInfo(52)];//仓库未开通
        }
        if($store->is_end != 1 ){
            return ['code'=>0,'msg'=>retStrInfo(208)];//仓库到期
        }
        if($store->state != 1 ){
            return ['code'=>0,'msg'=>retStrInfo(53)];//仓库冻结
        }

        //入库,扣货款
        //加入仓库
        DB::beginTransaction();
        try {
            $all_price = 0;
            foreach ($products as $k => $product){
                Log::info('第几次循环'.$product['sku_id']);
                if(!empty($product['sku_id'])){
                	$sku_list = SkuModel::where("id",$product['sku_id'])->first();
                	if($sku_list['sum'] < $product['num']){
                		return ['code'=>0,'msg'=>'库存不足'];
					}
					SkuModel::where('id',$product['sku_id'])->decrement('sum',$product['num']);
                    //$is_sku = 1; //多规格
                    $has = StoreGoodModel::where('sid', $sid)->where('gid', $product['product_id'])->where('sku_id',$product['sku_id'])->first();
                }else{
					$shop_list = ShopGoodModel::where("id",$product['product_id'])->first();
					if($shop_list['num'] < $product['num']){
						return ['code'=>0,'msg'=>'库存不足'];
					}
					ShopGoodModel::where('id',$product['product_id'])->decrement('num',$product['num']);
                    //$is_sku = 0; //单规格
                    $has = StoreGoodModel::where('sid', $sid)->where('gid', $product['product_id'])->first();
                }
               
                $shop = ShopGoodModel::where('id',$product['product_id'])->first();
                $cost = $shop['cost_price'];
                $sell = $shop['sell_price'];
                
                if($shop->state != 1 || empty($shop)){
                    Log::info('商品下架');
                    return ['code'=>0,'msg'=>retStrInfo(200)];//该商品已下架
                }

                    if (!empty($has)) {
                        $has->update([
                            'num' => $has->num + $product['num'],
                        ]);

                        $all_price += bcmul($shop['sell_price'],$product['num'],5);
                    } else {

                        if(empty($product['sku_id'])){
                           
                            $storegood = new StoreGoodModel();
                            Log::info("单规格");
                            $shop = ShopGoodModel::where('id',$product['product_id'])->first();
                            $storegood->sid = $sid;
                            $storegood->gid = $product['product_id'];
                            $storegood->gcost_price = $shop['cost_price'];
                            $storegood->gsell_price = $shop['sell_price'];
                            $storegood->num = $product['num'];
                            $all_price += bcmul($shop['sell_price'],$product['num'],5);
                            $storegood->save();
                            $sell = $shop['sell_price'];
                            $cost = $shop['cost_price'];
                        }else{
                            $storegood = new StoreGoodModel();
                            Log::info("多规格");
                            $sku = SkuModel::where('id',$product['sku_id'])->first();
                            $storegood->sid = $sid;
                            $storegood->sku_id = $product['sku_id'];
                            $storegood->gid = $product['product_id'];
                            $storegood->attr_name = $sku->property;
                            $storegood->gcost_price = $sku['cost_price'];
                            $storegood->gsell_price = $sku['sell_price'];
                            $storegood->num = $product['num'];
                            $all_price += bcmul($sku['gsell_price'],$product['num'],5);
                            $storegood->save();

                            $sell = $shop['sell_price'];
                            $cost = $shop['cost_price'];
                        }
                    }
                    $sn = StoreGoodLog::make_no_g();
                    StoreGoodLog::create([
                        'uid' => $uid,
                        'gid' => $product['product_id'],
                        'sku_id' => $product['sku_id'],
                        'cost' => $cost,
                        'sell' => $sell,
                        'num' => $product['num'],
                        'total' => $sell*$product['num'],
                        'sn' => $sn,
                    ]);
                //购物车去掉这个商品
                if(!empty($product['sku_id'])){
                    ShopCartModel::where('uid',$uid)->where('sku_id',$product['sku_id'])->delete();
                }else{
                    ShopCartModel::where('uid',$uid)->where('gid',$product['product_id'])->delete();
                }
            }
            $user_wallet = UserWalletModel::where('uid',$uid)->first();
            Log::info("当前货款和余额信息",['lock_money'=>$user_wallet['lock_money'],'all_price'=>$all_price]);
            if($user_wallet['lock_money'] < $all_price){
            	return ['code'=>0,'msg'=>'货款余额不足!'];
			}
            //扣货款
            UserWalletModel::handleAccount($uid,$all_price,'-','购物车入库',2,10);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['code'=>0,'msg'=>$exception->getMessage()];//抛出异常
        }
        return ['code'=>1,'msg'=>retStrInfo('201')];

    }
}
